package net.entelijan.cobean.util;

import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.entelijan.cobean.core.IConverter;
import net.entelijan.cobean.text.IllegalTextException;
import net.entelijan.cobean.text.converter.XMLGregorianCalendarTextConverter;

public class XMLGregorianCalendarConverter implements IConverter {

	private Log log = LogFactory.getLog(XMLGregorianCalendarConverter.class);

	private XMLGregorianCalendarTextConverter converter;

	public XMLGregorianCalendarConverter() {
		super();
		this.converter = new XMLGregorianCalendarTextConverter("yyyy-MM-dd");
	}

	public XMLGregorianCalendarConverter(String pattern) {
		super();
		this.converter = new XMLGregorianCalendarTextConverter(pattern);
	}

	@Override
	public String objectToString(Object object) {
		return converter.convertToString((XMLGregorianCalendar) object);
	}

	@Override
	public Object stringToObject(String string) {
		Object re;
		try {
			re = converter.convertToObject(string);
		} catch (IllegalTextException e) {
			String msg = "Could not convert 'string' to XMLGregorianCalendar. "
					+ e.getMessage();
			if (log.isDebugEnabled()) {
				log.error(msg, e);
			} else {
				log.error(msg);
			}
			re = "";
		}
		return re;
	}

}
